import cv2


def check_body(structure_str_list):
    if '</tbody>' not in structure_str_list:
        return False
    else:
        return True


def image_cut(image):
    height, width, _ = image.shape
    y = height // 2
    x = width // 2
    x = max(x, 200)
    image_top = cv2.imencode('.png', image[:y, :])[1].tobytes()
    image_left = cv2.imencode('.png', image[:, :x])[1].tobytes()
    return image_top, image_left


def get_table_row(structure_str_list_right):
    """
    mkdir if not exists, ignore the exception when multiprocess mkdir together
    """
    element = '<tbody>'
    if element not in structure_str_list_right:
        return 0
    index = structure_str_list_right.index(element)
    body_list = structure_str_list_right[index:]
    row = body_list.count('</tr>')
    return row


def structure_str_extend(structure_str_list_top, structure_str_list_right):

    element = '<tbody>'
    if '<tbody>' in structure_str_list_top:
        index = structure_str_list_top.index(element)
        indices = [i for i, x in enumerate(structure_str_list_top) if x == "<tr>"]
        body_list = structure_str_list_top[index:indices[-1]]
        row_list = structure_str_list_top[indices[-2]:indices[-1]]
        head_rows = body_list.count('</tr>')
        rows = get_table_row(structure_str_list_right)
        row_extend = rows - head_rows
        structure_str_list_top = structure_str_list_top[:indices[-1]]
        structure_str_list_top.extend(row_list * row_extend)
        structure_str_list_top.append('</tbody>')
    else:
        structure_str_list_top
    return structure_str_list_top